package cn.cjlmonster.demo02.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import cn.cjlmonster.demo02.R;

/**
 * This project is Demo02
 * Created by cjl on 2021/11/4 9:29 下午.
 */

public class TabAdapter extends RecyclerView.Adapter<TabAdapter.Holder> {

    private final LayoutInflater inflater;
    private final String[] mTabs;
    private OnItemSelectedListener listener;
    private int currentIndex;


    public TabAdapter(Context context, String[] mTabs, OnItemSelectedListener listener) {
        this.inflater = LayoutInflater.from(context);
        this.mTabs = mTabs;
        this.listener = listener;
        this.currentIndex = 0;
    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.item_tab, parent, false);
        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull Holder holder, int position) {
        boolean isSelected = currentIndex == position;
        holder.itemView.setActivated(isSelected);
        holder.tv_tab.setText(mTabs[position]);
        final int index = position;
        holder.itemView.setOnClickListener(v -> {
            if (currentIndex != index) {
                currentIndex = index;
                notifyDataSetChanged();
                listener.onItemSelected(index, mTabs[index]);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mTabs.length;
    }

    static class Holder extends RecyclerView.ViewHolder {

        TextView tv_tab;

        public Holder(@NonNull View itemView) {
            super(itemView);
            tv_tab = itemView.findViewById(R.id.tv_tab);
        }
    }

    public interface OnItemSelectedListener {
        void onItemSelected(int position, String tab);
    }
}
